package city.spring.modules.consumptionItem.controller;

import city.spring.modules.consumptionItem.entity.ConsumptionCategoryEntity;
import city.spring.modules.consumptionItem.service.ConsumptionCategoryService;
import city.spring.modules.consumptionItem.vo.ConsumptionCategoryEntityVO;
import city.spring.utils.MyBatisUtils;
import city.spring.utils.TreeDataUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ListMultimap;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Controller：收费项目类别
 *
 * @author pxm
 * @date 2020-08-05 16:19:31
 */
@RestController
@RequestMapping("/consumption_category")
public class ConsumptionCategoryController extends ApiController {
    private final ConsumptionCategoryService consumptionCategoryService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<ConsumptionCategoryEntity, ?>> entityOrderFields;

    public ConsumptionCategoryController(ConsumptionCategoryService consumptionCategoryService) {
        this.consumptionCategoryService = consumptionCategoryService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(ConsumptionCategoryEntity::getId);
        entityOrderFields.add(ConsumptionCategoryEntity::getTitle);
        entityOrderFields.add(ConsumptionCategoryEntity::getPid);
        entityOrderFields.add(ConsumptionCategoryEntity::getStandardPrice);
        entityOrderFields.add(ConsumptionCategoryEntity::getDepartment);
        entityOrderFields.add(ConsumptionCategoryEntity::getDescribes);
        entityOrderFields.add(ConsumptionCategoryEntity::getGmtCreate);
        entityOrderFields.add(ConsumptionCategoryEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>收费项目类别</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, ConsumptionCategoryEntity entity) {
        LambdaQueryChainWrapper<ConsumptionCategoryEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 获取全部的 <strong>多级收费项目信息</strong> 列表
     */
    @GetMapping("categorytree")
    public Object listAll() {
        List<ConsumptionCategoryEntity> list = consumptionCategoryService.list();
        ListMultimap<String, ConsumptionCategoryEntity> datasource = TreeDataUtils.handlerTreeDatasource(list, "", ConsumptionCategoryEntity::getId, ConsumptionCategoryEntity::getPid, ConsumptionCategoryEntity::getChildren, ConsumptionCategoryEntity::setChildren);
        return success(datasource.values());
    }

    /**
     * 分页获取 <strong>收费项目类别</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, ConsumptionCategoryEntityVO entity) {
        QueryWrapper<? extends ConsumptionCategoryEntity> queryWrapper = buildQuery(entity);
        return success(consumptionCategoryService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, ConsumptionCategoryEntity entity) {
//        LambdaQueryChainWrapper<ConsumptionCategoryEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<ConsumptionCategoryEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }

    /**
     * 获取全部的 <strong>多级分类信息</strong> 列表
     */
    @GetMapping("tree")
    public Object listTree(@PageableDefault(sort = {"sorted"}) Pageable pageable, ConsumptionCategoryEntity entity) {
        LambdaQueryChainWrapper<ConsumptionCategoryEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        List<ConsumptionCategoryEntity> list = lambdaQuery.list();

        return success(consumptionCategoryService.converterToTreeDatasource(list));
    }

    /**
     * 以 父级ID 获取全部的 <strong>菜单信息</strong> 列表
     */
    @GetMapping("list-pid-{pid}")
    public Object listPid(@PathVariable(required = false) String pid, @PageableDefault(sort = {"sorted"}) Pageable pageable, ConsumptionCategoryEntity entity) {
        LambdaQueryChainWrapper<ConsumptionCategoryEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        // 搜索条件是否为空
        boolean emptyOfWhere = lambdaQuery.getWrapper().isEmptyOfWhere();
        if (StringUtils.isNotBlank(pid)) {
            lambdaQuery.eq(emptyOfWhere, ConsumptionCategoryEntity::getPid, pid);
        } else {
            // pid 为 null 或者 空字符串
            lambdaQuery.eq(emptyOfWhere, ConsumptionCategoryEntity::getPid, "")
                    .or()
                    .isNull(ConsumptionCategoryEntity::getPid);
        }
        List<ConsumptionCategoryEntity> list = lambdaQuery.list();

        // 这里处理树形结构数据的时候，不自动加载父级信息，因为会与前端已有的数据冲突
        return success(consumptionCategoryService.converterToTreeDatasource(list, false));
    }

    /**
     * 获取 pid为null的 消费项目类别 列表展示（子(小)类别）
     *
     * @return
     */
    @GetMapping("/getLittleCategory")
    public Object getLittleCategory() {
        return success(consumptionCategoryService.getLittleCategory());
    }

    /**
     * 获取 pid不为null的 消费项目类别 列表展示（父类别）
     *
     * @return
     */
    @GetMapping("/getFatherCategory")
    public Object getFatherCategory() {
        return success(consumptionCategoryService.getFatherCategory());
    }

    /**
     * 获取一个 <strong>收费项目类别</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        QueryWrapper<ConsumptionCategoryEntityVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t3.id", id);
        List<ConsumptionCategoryEntityVO> records = consumptionCategoryService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>收费项目类别</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody ConsumptionCategoryEntity entity) {
        consumptionCategoryService.saveConsumptionCategory(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>收费项目类别</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody ConsumptionCategoryEntity entity) {
        entity.setId(id);
        consumptionCategoryService.updateConsumptionCategory(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>收费项目类别</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        consumptionCategoryService.deleteConsumptionCategory(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>收费项目类别</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        consumptionCategoryService.deleteConsumptionCategory(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<ConsumptionCategoryEntity> buildLambdaQuery(ConsumptionCategoryEntity entity) {
        LambdaQueryChainWrapper<ConsumptionCategoryEntity> lambdaQuery = consumptionCategoryService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), ConsumptionCategoryEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTitle()), ConsumptionCategoryEntity::getTitle, entity.getTitle());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPid()), ConsumptionCategoryEntity::getPid, entity.getPid());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDepartment()), ConsumptionCategoryEntity::getDepartment, entity.getDepartment());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDescribes()), ConsumptionCategoryEntity::getDescribes, entity.getDescribes());
        lambdaQuery.eq(entity.getGmtCreate() != null, ConsumptionCategoryEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, ConsumptionCategoryEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<? extends ConsumptionCategoryEntity> buildQuery(ConsumptionCategoryEntityVO entity) {
        QueryWrapper<? extends ConsumptionCategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t3.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getPtitle()), "t3.ptitle", entity.getPtitle());
        wrapper.like(StringUtils.isNotBlank(entity.getPid()), "t3.pid", entity.getPid());
        wrapper.like(StringUtils.isNotBlank(entity.getTitle()), "t3.title", entity.getTitle());
        wrapper.eq(entity.getStandardPrice() != null, "t3.title", entity.getStandardPrice());
        wrapper.like(StringUtils.isNotBlank(entity.getDeptName()), "t4.title", entity.getDeptName());
        wrapper.like(StringUtils.isNotBlank(entity.getDescribes()), "t3.describes", entity.getDescribes());
        wrapper.eq(entity.getGmtCreate() != null, "t3.gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "t3.gmt_modified", entity.getGmtModified());
        return wrapper;
    }


    @GetMapping("getConsumptionCategoryById/{id}")
    public Object getConsumptionCategoryById(@PathVariable String id) {
        return success(consumptionCategoryService.getConsumptionCategoryById(id));
    }
}
